#include "event_driver.h"
#include "tcp_client.h"
#include "async_client.h"
#include <boost/thread.hpp>
#include <boost/cstdint.hpp>
#include <iostream>
#include <iomanip>

using namespace auroral::event;
using namespace boost;
using namespace std;
using namespace async_client;

const int16_t SERVER_PORT = 8899;

auroral::event::EventDriver eventDriver;

int ping_handle(auroral::event::EventDriver &eventDriver, string eventType, shared_ptr<void> data);
int pong_handle(auroral::event::EventDriver &eventDriver, string eventType, shared_ptr<void> data);
int undef_msg_handle(auroral::event::EventDriver &eventDriver, string eventType, shared_ptr<void> data);
int do_ping_handle(auroral::event::EventDriver &eventDriver, string eventType, shared_ptr<void> data);
int do_pong_handle(auroral::event::EventDriver &eventDriver, string eventType, shared_ptr<void> data);

int main(int argc, char *argv[])
{
	eventDriver.registerEvent("ping");
	eventDriver.registerEvent("pong");
	eventDriver.registerEvent("do_ping");
	eventDriver.registerEvent("do_pong");
	eventDriver.registerEvent("undef");

	eventDriver.addHandle("ping", ping_handle);
	eventDriver.addHandle("pong", pong_handle);
	eventDriver.addHandle("do_ping", do_ping_handle);
	eventDriver.addHandle("do_pong", do_pong_handle);
	eventDriver.addHandle("undef", undef_msg_handle);

	boost::thread thread2(boost::bind(&auroral::event::EventDriver::exec, &eventDriver));

	boost::asio::io_service io_service1;
	AsyncClient client(io_service1, "localhost", SERVER_PORT);
	client.active();
	boost::thread thread1(boost::bind(&boost::asio::io_service::run, &io_service1));

	int i = 0;
	for(;;)
	{
		stringstream ss;
		ss.clear();
		ss << setw(10) << setfill('0') << i++ << "\r\n";
		shared_ptr<PING_INFO> ping_info = shared_ptr<PING_INFO>(new PING_INFO);
		ping_info->client = &client;
		ping_info->message = ss.str();
		eventDriver.emitEvent("do_ping", ping_info);
		this_thread::sleep(posix_time::microseconds(1));
	}
	thread1.join();
	thread2.join();

}